'use strict';

app.controller('summaryCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$modal', 'lodash', function ($scope, $http, $stateParams, $rootScope, $modal, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $scope.statusName = "";
    $scope.brdList = [];
    $scope.projectPlanList = [];
    $scope.productLine = [];
    $scope.accountList = [];
    $scope.reqDetails = {};
    $scope.info = {
        sltStatus : "0",
        sltBrdId  : "0",
    };
    $scope.levelItem       = "";
    $scope.projectPlanItem = "";
    $scope.brdItem         = "";
    $scope.sltUser         = "";
    $scope.sltLineItem     = "";
    // $scope.info.edit.content = {};
    //$scope.sltLineItem     = [{"id":"BU2018011614042700001","name":"add_flow_test1","level":"1","parentId":"BU2018011609513500002","isDel":"1","children":[],"isExpanded":false,"isActive":false,"selected":true}];
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    var saveBtn = {
        show : $rootScope.isMatrixRole(),
        label: '保存',
        func : function() {
            updateReqDetails();
        }
    };
    var backUrl = {
        show : true,
        label: "返回",
        func : function() {
            $rootScope.backHistory();
        }
    };
    if($rootScope.isUserCanOperateByRole('pdm')){
        $scope.settings.btnEle.push(saveBtn);
    }
    $scope.settings.btnEle.push(backUrl);
    //结束headerElement设置

    initValue();
    getProjectPlanList([]);

    //初始化数据
    function initValue() {
        angular.forEach(cLevel, function(level) {
            level.crtname = level.name;
        });
        $scope.cLevel  = cLevel;
    };


    //获取项目计划列表
    function getProjectPlanList(brdList) {
        var url = matrix_product_url +"/projectPlan/getProjectPlans?containFinished=Y";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    angular.forEach(result.data, function(projectPlan) {
                        projectPlan.crtname = projectPlan.projectPlanName;
                    });
                    $scope.projectPlanList = result.data;
                    getProductLine(brdList, result.data);
                } else {
                    $rootScope.toasterErrorInfo("获取projectPlan列表数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取产品线集合
    function getProductLine(brdList, projectPlanList) {
        var url = matrix_product_url +"/productLine/getProductLineTree";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.productLine = result.data.children;
                var array = [];
                var oneLevelArray = flattenDeep(result.data.children, array);
                getUserList(brdList, projectPlanList, oneLevelArray);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //将多级数据改成一级
    function flattenDeep(data, array) {
        angular.forEach(data, function(d) {
            array.push(d);
            if(d.children && d.children.length) {
                flattenDeep(d.children, array);
            }
        });
        return array;
    };

    //获取用户集合
    function getUserList(brdList, projectPlanList, oneLevelArray) {
        var url = beetle_auth_url +"/user/?token_id=" + getTokenId();
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    angular.forEach(result.data, function(data) {
                        data.crtname = data.realname;
                    });
                    $scope.accountList = result.data;
                    getReqDetails(brdList, projectPlanList, oneLevelArray, result.data);
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //获取需求详情
    function getReqDetails(brdList, projectPlanList, oneLevelArray, userList) {
        var url = matrix_product_url +"/brdRequirement/getBrdRequirements?withFeatureDesc=0&reqId="+ $stateParams.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    $scope.reqDetails = result.data[0];
                    $scope.breadcrumb.push('产品设计',$scope.reqDetails.reqName);
                    // $scope.reqDetails.reqDesc = lodash.trim($scope.reqDetails.reqDesc, "</p>");
                    //给优先级设置值
                    $scope.levelItem = $scope.reqDetails.reqPriority == null ? "" : lodash.findWhere(cLevel, {"level": $scope.reqDetails.reqPriority});
                    //给关联BRD设置值
                    $scope.brdItem = $scope.reqDetails.brdId == null ? "" : lodash.findWhere(brdList, {"brdId": $scope.reqDetails.brdId});
                    //给项目计划设置值
                    $scope.projectPlanItem = $scope.reqDetails.projectPlanId == null ? "" : lodash.findWhere(projectPlanList, {"projectPlanId": $scope.reqDetails.projectPlanId});
                    //给PDM负责人设置值
                    $scope.sltUser = $scope.reqDetails.reqChargerAccount == null ? lodash.findWhere(userList, {"account": getUserAccount()}) : lodash.findWhere(userList, {"account": $scope.reqDetails.reqChargerAccount});
                    //给产品线设置值
                    $scope.sltLineItem = $scope.reqDetails.productLineId == null ? "" : lodash.findWhere(oneLevelArray, {"id": $scope.reqDetails.productLineId});
                    getBrdType($scope.reqDetails.reqStatus);
                } else {
                    $rootScope.toasterErrorInfo("获取需求详情数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };




    //选择优先级
    $scope.selectlevelItem = function(item) {
        $scope.reqDetails.reqPriority = item.level;
    };

    //选择关联BRD
    $scope.selectBrdItem = function(item) {
        $scope.reqDetails.brdId = item.brdId;
    };

    //选择项目计划
    $scope.selectProjectPlanItem = function(item) {
        $scope.reqDetails.projectPlanId = item.projectPlanId;
    };

    //选择产品线
    $scope.sltProductLine = function(item) {
        $scope.sltLineItem = item;
        $scope.reqDetails.productLineId = item.id;
    };

    //取消选择的产品线
    $scope.cancelProductLine = function() {
        $scope.sltLineItem = {"name": "请选择产品线"};
        $scope.reqDetails.productLineId = null;
    };

    //选择PDM负责人
    $scope.selectUserItem = function(item) {
        $scope.reqDetails.reqChargerAccount = item.account;
        $scope.reqDetails.reqChargerRealname = item.realname;
    };

    //获取brd type
    function getBrdType(reqStatus) {
        var url = sys_config_url +"/select/get?type=BRD_STATUS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.statusName = lodash.findWhere(result.data.BRD_STATUS, {"key": reqStatus}).value;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    function updateReqDetails() {
        if(!$scope.reqDetails.reqName) {
            $(".form-req-name").focus();
            $rootScope.toasterWarningInfo("标题不能为空！");
            return false;
        }
        if(!$scope.reqDetails.reqDesc) {
            $(".form-req-desc").focus();
            $rootScope.toasterWarningInfo("描述不能为空！");
            return false;
        }
        $scope.reqDetails.reqUpdateAccount=getUserAccount();
        $scope.reqDetails.reqUpdateRealname=getUserName();

        var url = matrix_product_url +"/brdRequirement/saveBrdRequirement";
        $http({
            method  : "post",
            url     : url,
            data    : JSON.stringify($scope.reqDetails),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                $rootScope.toasterSuccessInfo("修改成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

}]);